import 'package:ds18LedBtc/search/search_row.dart';
import 'package:flutter/material.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import '../tool/assets.dart';

class SearchView extends StatefulWidget {
  const SearchView({super.key});

  @override
  State<SearchView> createState() => _SearchViewState();
}

class _SearchViewState extends State<SearchView> implements BLESearchTableViewDelegate {
  BLESearchTableView? _tableView;
  BLESearchTableViewDelegate? delegate;
  bool _isGroupManager = false;
  String filterName = 'Triones';
  // String filterName = 'QHM';
  List<String> list1 = ['Refresh Device List', 'Group Management'];
  List<String> list2 = [assets.add, assets.back2];
  @override
  void initState() {
    super.initState();
    delegate = this;
    _tableView = BLESearchTableView(
        filterName: [filterName],
        agreement: delegate,
        contentColor: Colors.transparent,
        // dragDecoration: BoxDecoration(
        //     color: Colors.black,
        //     borderRadius: BorderRadius.circular(10),
        //     boxShadow: [BoxShadow(color: Colors.white.withOpacity(0.5), blurRadius: 2)]),
        // dragTransformXY: Offset(1.0, 1.2),
        bgViewForHeader: (child) => Container(color: Colors.transparent, child: child),
        bgViewForFooter: (child) => Container(color: Colors.transparent, child: child));
  }

  void clickBottom(String text, BuildContext context) {
    switch (text) {
      case 'Refresh Device List':
        _tableView?.refreshKey?.currentState?.show();
        break;
      case 'Group Management':
      case assets.back2:
        _isGroupManager = !_isGroupManager;
        _tableView?.isGroupManager = _isGroupManager;
        setState(() {});
        break;
      case assets.add:
        var input = TextAlertDialog(
          title: const Text('Add', style: TextStyle(fontSize: 20)),
          sheet: ['Cancel', 'OK'].map(($0) => Text($0)).toList(),
          contentColor: Color_alert_view,
          onDone: (p0, p1) {
            if (p0 == 'OK' || p0 == 'Done') {
              _tableView?.addGroup(p1);
              Navigator.pop(context);
            } else if (p0 == 'Cancel') {
              Navigator.pop(context);
            }
            print('==========> tag = ${p0}, value = ${p1}');
            return true;
          },
        );

        input.show(context);
        break;
      default:
    }
  }

  @override
  Widget build(BuildContext context) {
    double statusBarHeight = MediaQuery.of(context).padding.top;
    double appBarHeight = AppBar().preferredSize.height;

    return Scaffold(
      resizeToAvoidBottomInset: false, // 确保键盘弹出时，页面不自动调整大小
      extendBodyBehindAppBar: true, // 允许AppBar背景延伸到屏幕上方
      appBar: AppBar(
        title: _isGroupManager ? const Text('GROUP MANAGEMENT') : Image.asset(assets.DS18, height: 30),
        leading: IconButton(
            onPressed: () {
              Navigator.pop(context);
            },
            icon: Image.asset(assets.back1, width: 25, height: 25)),
      ),
      body: Stack(
        children: [
          ///背景
          Positioned(
            child: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(image: AssetImage(assets.bg_search), fit: BoxFit.fitHeight),
              ),
            ),
          ),

          Positioned(
            left: 10,
            right: 10,
            top: statusBarHeight + appBarHeight,
            height: 40,
            child: const Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Ungrouped Devices',
                style: TextStyle(color: Colors.white, fontSize: 18),
              ),
            ),
          ),

          ///tableview
          Positioned(
              bottom: 80,
              left: 10,
              right: 10,
              top: statusBarHeight + appBarHeight + 40,
              child: Container(
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(10), color: Colors.transparent),
                  clipBehavior: Clip.hardEdge, // 通过clipBehavior来切割子组件
                  child: _tableView ?? Container())),

          ///底部按钮
          Positioned(
              bottom: 20,
              right: 0,
              left: 0,
              height: 40,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: (_isGroupManager ? list2 : list1).map(($0) {
                    if (_isGroupManager) {
                      return Container(
                        width: 40,
                        height: 40,
                        child: InkWell(
                          borderRadius: BorderRadius.circular(25),
                          onTapUp: (_) => clickBottom($0, context),
                          child: Image.asset($0, width: 20, height: 40),
                        ),
                      );
                    }
                    return Material(
                        color: Colors.transparent, // 保证 Material 背景透明
                        child: Ink(
                          decoration: BoxDecoration(
                            color: Colors.white, // 设置背景颜色
                            borderRadius: BorderRadius.circular(4), // 圆角
                          ),
                          child: InkWell(
                            borderRadius: BorderRadius.circular(4),
                            onTapUp: (_) => clickBottom($0, context),
                            child: Padding(
                              padding: const EdgeInsets.only(left: 10, right: 10),
                              child: Center(child: Text($0, style: const TextStyle(fontSize: 16, color: Colors.black))),
                            ),
                          ),
                        ));
                  }).toList()))
        ],
      ),
    );
  }

  @override
  List<RowModel> listModelForFooter(String appVersion) => [];

  @override
  List<RowModel> listModelForHeader(String appVersion) => [];

  @override
  List<RowModel> listModelForSection(List<String> list) {
    return list
        .map(($0) => RowModel(
            text: $0,
            height: 40,
            textStyle: const TextStyle(fontSize: 18, color: Colors.white),
            lineColor: Color_line_view,
            lineHeight: 1,
            bgColor: Colors.transparent,
            iconName: assets.delete,
            leftOffset: 0,
            showLine: false,
            iconSize: 20))
        .toList();
  }

  @override
  void methodForClickBLESearchTableView(BLESearchTableViewClickType type, String tag) {}

  @override
  Widget viewForRowInSection(DSPeripheral peripheral, int section, int row, bool isOn) {
    var type = SearchItemType.middlle;
    if (row == 0 && _tableView!.deviceList[section].values.first.length - 1 == row) {
      type = SearchItemType.topBottom;
    } else if (row == 0) {
      type = SearchItemType.top;
    } else if (row == _tableView!.deviceList[section].values.first.length - 1) {
      type = SearchItemType.bottom;
    }
    return SearchItem(
      device: peripheral,
      isManager: _isGroupManager,
      type: type,
      onSelect: () => _tableView?.clickDevice(section, row),
      onPressLongToChangeName: () => _tableView?.changeDeviceName(section, row, peripheral.peripheral),
    );
  }
}
